import json
import csv
import os
from datetime import datetime
from typing import List, Dict, Optional

class GameDataParser:
    def parse(self, raw_data: dict) -> List[Dict]:
        """
        解析原始Steam API数据，提取游戏信息
        返回结构: [{'name': str, 'price': float, 'rating': int}]
        """
        games = []
        
        # 获取热销商品列表（Steam API的主要数据结构）
        top_sellers = raw_data.get('top_sellers', {})
        items = top_sellers.get('items', [])
        
        # 处理每个游戏项目
        for item in items:
            try:
                # 提取基本信息
                name = item.get('name', 'Unknown Game')
                
                # 处理价格（转换为美元，除以100）
                final_price = item.get('final_price', 0)
                price = final_price / 100.0
                
                # 处理好评率（处理可能的缺失值）
                reviews = item.get('reviews', {})
                all_reviews = reviews.get('all', {})
                rating = all_reviews.get('percent', 0)  # 默认0如果无评分
                
                # 添加到结果列表
                games.append({
                    'name': name,
                    'price': price,
                    'rating': rating
                })
                
            except (TypeError, KeyError) as e:
                # 跳过解析失败的项目
                print(f"解析游戏数据时出错: {e}")
                continue
        
        print(f"成功解析 {len(games)} 款游戏数据")
        return games

class DataStorage:
    def __init__(self, output_dir: str = 'output'):
        self.output_dir = output_dir
        os.makedirs(output_dir, exist_ok=True)
    
    def save_json(self, data: List[Dict], filename: str):
        """保存数据为JSON文件"""
        filepath = os.path.join(self.output_dir, filename)
        
        # 添加时间戳
        timestamp = datetime.now().isoformat()
        data_with_meta = {
            'timestamp': timestamp,
            'game_count': len(data),
            'games': data
        }
        
        with open(filepath, 'w', encoding='utf-8') as f:
            json.dump(data_with_meta, f, indent=2, ensure_ascii=False)
        
        print(f"已保存JSON数据到 {filepath} (包含 {len(data)} 款游戏)")
    
    def save_csv(self, data: List[Dict], filename: str):
        """保存数据为CSV文件（增量存储）"""
        filepath = os.path.join(self.output_dir, filename)
        timestamp = datetime.now().isoformat()
        
        # 检查文件是否存在以确定是否需要写入表头
        file_exists = os.path.exists(filepath)
        
        with open(filepath, 'a', newline='', encoding='utf-8') as f:
            writer = csv.DictWriter(f, fieldnames=['timestamp', 'name', 'price', 'rating'])
            
            if not file_exists:
                writer.writeheader()
            
            # 写入每条游戏记录并添加时间戳
            for game in data:
                row = game.copy()
                row['timestamp'] = timestamp
                writer.writerow(row)
        
        print(f"已追加 {len(data)} 条游戏数据到CSV文件 {filepath}")

# 测试代码
if __name__ == "__main__":
    # 模拟API返回的原始数据
    raw_data = {
        "top_sellers": {
            "id": "top_sellers",
            "name": "Top Sellers",
            "items": [
                {
                    "id": 570,
                    "name": "Dota 2",
                    "final_price": 0,
                    "reviews": {
                        "all": {
                            "percent": 88,
                            "total": "1,234,567"
                        }
                    }
                },
                {
                    "id": 730,
                    "name": "Counter-Strike: Global Offensive",
                    "final_price": 0,
                    "reviews": {
                        "all": {
                            "percent": 92,
                            "total": "5,678,901"
                        }
                    }
                },
                {
                    "id": 578080,
                    "name": "PUBG: BATTLEGROUNDS",
                    "final_price": 0,
                    "reviews": {
                        "all": {
                            "percent": 76,
                            "total": "1,234,567"
                        }
                    }
                },
                {
                    "id": 1172470,
                    "name": "Apex Legends™",
                    "final_price": 0,
                    "reviews": {
                        "all": {
                            "percent": 85,
                            "total": "678,901"
                        }
                    }
                },
                {
                    "id": 271590,
                    "name": "Grand Theft Auto V",
                    "final_price": 2999,  # $29.99
                    "reviews": {
                        "all": {
                            "percent": 94,
                            "total": "789,012"
                        }
                    }
                },
                {
                    "id": 1085660,
                    "name": "Destiny 2",
                    "final_price": 0,
                    "reviews": {}  # 测试缺失评分的情况
                }
            ]
        }
    }
    
    # 实例化解析器
    parser = GameDataParser()
    parsed_data = parser.parse(raw_data)
    
    # 打印解析结果
    print("\n解析结果示例:")
    for i, game in enumerate(parsed_data[:3], 1):
        print(f"{i}. {game['name']} - ${game['price']:.2f} - 好评率: {game['rating']}%")
    
    # 实例化存储器
    storage = DataStorage()
    
    # 保存为JSON
    storage.save_json(parsed_data, "steam_games.json")
    
    # 保存为CSV（多次调用测试增量存储）
    storage.save_csv(parsed_data, "steam_games.csv")
    print("再次调用save_csv测试增量存储...")
    storage.save_csv(parsed_data, "steam_games.csv")
    
    print("\n测试完成！请检查output目录下的文件")
